package com.tz.controller;

import com.alibaba.fastjson.JSON;
import com.tz.entity.Account;
import com.tz.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by yejf on 2017/1/12.
 */
@Controller
@RequestMapping(value = "/ajax")
public class AjaxController {

    @Autowired
    private IAccountService accountService;

    @RequestMapping(value = "/plain", produces = "text/plain")
    @ResponseBody //将内容直接返回，无需视图显示
    public String getPlainText(HttpServletRequest request) {
        //获取请求参数
        String name = request.getParameter("name");
        //判断
        if(name.equals("admin") || name.equals("root")) {
            return "1"; //表示不可以用
        } else {
            return "0";  //表示可以用
        }
    }

    @ResponseBody
//    @RequestMapping(value = "/json", produces = "text/json;charset=UTF-8",method = RequestMethod.POST)
    @RequestMapping(value = "/json", produces = "text/json;charset=UTF-8")  //此处写 text/json 和 application/json 都可以
    public String getJsonText(HttpServletRequest request) {
        //调用业务方法获取集合数据
        List<Account> list = accountService.list();
        //把集合转换成 json字符串
        String jsonStr = JSON.toJSONString(list);
        System.out.println("得到的json字符串：\n"+jsonStr);
        //返回
        return jsonStr;
    }

    @ResponseBody
    @RequestMapping(value = "/json2", produces = "application/json;charset=UTF-8")  //此处必需写 application/json,如果写text/json 会出现 406 错误
    public List<Account> getSpringJosn() {  //返回值可以是任意对象，或直接写 Object 也可以
        //调用业务方法获取集合数据
        List<Account> list = accountService.list();
        //使用spring自带的json解析能力,需要依赖 jackson 相关的依赖
        System.out.println(list);
        //
        return list;
    }

    @ResponseBody
    @RequestMapping(value = "/xml/{id}", produces = "application/xml;charset=UTF-8",method = RequestMethod.GET)  // 注解：以XML为MIME-TYPE返回给客户端时，要求对象要打上@XMLRootElement注解
    public Account getXmlData(@PathVariable("id") Long id) {
        System.out.println("获取id为"+id+" 的帐户信息");
        Account a = accountService.get(id);
        System.out.println(a);
        return a;
    }
}
